#include <stdint.h>
#include <string.h>
#include "app_utils.h"

#define EINVAL              1

static int char2hex(const char *c, uint8_t *x)
{
    if (*c >= '0' && *c <= '9')
    {
        *x = *c - '0';
    }
    else if (*c >= 'a' && *c <= 'f')
    {
        *x = *c - 'a' + 10;
    }
    else if (*c >= 'A' && *c <= 'F')
    {
        *x = *c - 'A' + 10;
    }
    else
    {
        return -EINVAL;
    }

    return 0;
}

int str_2_bdaddr(const char *str, bd_addr_t *addr)
{
    int i, j;
    uint8_t tmp;

    if (strlen(str) != 17)
    {
        return -EINVAL;
    }

    for (i = 5, j = 1; *str != '\0'; str++, j++)
    {
        if (!(j % 3) && (*str != ':'))
        {
            return -EINVAL;
        }
        else if (*str == ':')
        {
            i--;
            continue;
        }

        addr->addr[i] = addr->addr[i] << 4;

        if (char2hex(str, &tmp) < 0)
        {
            return -EINVAL;
        }

        addr->addr[i] |= tmp;
    }

    return 0;
}

/**
 * @brief Change char into hex
 * eg: 'a' -> 0x0a
 */
uint8_t char_2_hex(const char c)
{
    if (c >= '0' && c <= '9')
    {
        return(c - '0');
    }
    else if (c >= 'a' && c <= 'f')
    {
        return(c - 'a' + 10);
    }
    else if (c >= 'A' && c <= 'F')
    {
        return(c - 'A' + 10);
    }
    return 0;
}

uint8_t checksum(uint8_t *pdata, uint16_t len)
{
    uint8_t sum = 0;
    for (int i=0; i<len; i++)
    {
        sum += pdata[i];
    }
    return sum;
}
